#include "Client.h"

int RecvFile(int sockfd){
    int judge = 0;
    recv(sockfd, &judge, sizeof(int), 0);
    if(judge == -1){
        printf("error file\n");
        return -1;
    }
    FileBuf_t filemsg;
    recv(sockfd, &filemsg, sizeof(FileBuf_t), MSG_WAITALL);

    int fd = open(filemsg.buf, O_RDWR|O_CREAT|O_TRUNC, 0666);
    off_t filesize = filemsg.size;

    int cursize = 0;
    while(cursize < filesize){
        //清空数据
        bzero(filemsg.buf, sizeof(filemsg.buf));
        //读数据
        recv(sockfd, &filemsg.size, sizeof(int), 0);
        int ret = 0;
        while(ret < filemsg.size){
            ret = recv(sockfd, &filemsg.buf, sizeof(filemsg.buf), MSG_NOSIGNAL);
            write(fd, filemsg.buf, filemsg.size);
            cursize += filemsg.size;
        }
    }
   // struct stat file;
   // fstat(fd, &file);
   // if(file.st_size != filesize){
   //     close(fd);
   //     return -1;
   // }

    close(fd);
    printf("FINISH\n");
    return 0;
}
int TransFile(int sockfd, char *pathname){
    // 上传文件名
    int fd = open(pathname, O_RDWR);
    send(sockfd, &fd, sizeof(int), 0);
    if(fd == -1){
        printf("%s is not existence!\n", pathname);
        return 0;
    }
    struct stat file;
    fstat(fd, &file);

    FileBuf_t filemsg;
    char *filename = strtok(pathname, " /");
    memcpy(filemsg.buf, filename, strlen(filename));
    while(filename != NULL){
        memcpy(filemsg.buf, filename, strlen(filename));
        filename = strtok(NULL, " /");
    }
    //告知文件名与大小
    filemsg.size = file.st_size;
    printf("filename == %s\n", filemsg.buf);
    printf("fil\n");
    send(sockfd, &filemsg, sizeof(FileBuf_t), 0);
    int cursize = 0;
    while(cursize < file.st_size){
        //清空数据
        bzero(filemsg.buf, sizeof(filemsg.buf));
        //读数据
        filemsg.size = read(fd, filemsg.buf, sizeof(filemsg.buf));
        send(sockfd, &filemsg.size, sizeof(int), MSG_NOSIGNAL);
        send(sockfd, &filemsg.buf, sizeof(filemsg.buf), MSG_NOSIGNAL);
        cursize += filemsg.size;
    }
    printf("FINISH\n");
    close(fd);
    return 0;
}


